package com.hqd.ch03.v7;

import com.hqd.ch03.v7.config.BeanDefinition;
import com.hqd.ch03.v7.config.MutablePropertyValues;
import com.hqd.ch03.v7.io.ResourceLoader;
import com.hqd.ch03.v7.io.support.DefaultResourceLoader;
import com.hqd.ch03.v7.registry.BeanDefinitionRegistry;
import com.hqd.ch03.v7.registry.SimpleBeanDefinitionRegistry;
import org.apache.commons.beanutils.BeanUtils;

public abstract class SpringImitationV7 {
    protected BeanDefinitionRegistry beanDefinitionRegistry = new SimpleBeanDefinitionRegistry();
    /**
     * 资源加载器
     */
    protected ResourceLoader resourceLoader = new DefaultResourceLoader();

    private void initBean(Object bean, BeanDefinition bd) {
        try {
            MutablePropertyValues properties = bd.getProperties();
            properties.getProperties().keySet().forEach(name -> {
                String value = properties.getValue(name);
                try {
                    BeanUtils.setProperty(bean, name, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private Object createBean(BeanDefinition bd) {
        try {
            String beanClass = bd.getBeanClass();
            Object o = Class.forName(beanClass).getConstructor().newInstance();
            initBean(o, bd);
            return o;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> T getBean(String beanName, Class<T> clazz) {
        BeanDefinition bd = beanDefinitionRegistry.getBeanDefinition(beanName);
        return (T) createBean(bd);
    }


    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}
